//
//  APIHSBCTotal.m
//  Bracelet
//
//  Created by steve on 15-3-12.
//  Copyright (c) 2015年 jing zhao. All rights reserved.
//

#import "APIHSBCTotal.h"
#import "APIConnection.h"
#import "FileReadAndWrite.h"
#define FILENAMECACHE_APIHSBCTOTAL @"fileName_apiHsbcTotal"
@implementation APIHSBCTotal

-(instancetype)initWithHSBCTotalData:(NSDictionary *)totalDic{
  self = [super init];
  if (self) {
    self.nextChallenge = [totalDic objectForKey:APIKEYNEXTCHALLENGE];
    self.distanceToNextCity = [totalDic objectForKey:APIKEYDISTANCETONEXTCITY];
    self.totalWalkers = [totalDic objectForKey:APIKEYTOTALWALKERS];
    self.nextCityName = [totalDic objectForKey:APIKEYNEXTCITY_EN];
    self.loadedHTML = [totalDic objectForKey:APIKEYHTML];
  }
  return self;
}

+(instancetype)initWithHSBCData:(NSDictionary *)totalDic{
  return [[self alloc]initWithHSBCTotalData:totalDic];
}

+(void)getHSBCTotalSuccess:(void (^)(APIHSBCTotal *hsbcTotal))successBlock
                   failure:(void (^)( NSError *error)) failureBlock{
  NSString *strUserId = [[NSUserDefaults standardUserDefaults]objectForKey:USERID];
  NSDictionary *headerData =@{@"BasicAuthUsername":strUserId};
    NSDictionary *data = @{@"ios_android_flag":@"ios"};
  
  [[APIConnection shareInstance]post:@"hbcn/hbcnTotal" data:data header:headerData netError:^(NSError *error) {
    failureBlock(error);
    
    //取缓存
    NSDictionary *dicCanch = [FileReadAndWrite getTheStorageDataWithFile:FILENAMECACHE_APIHSBCTOTAL];
    if (dicCanch) {
      NSDictionary *dicSuccess = [dicCanch objectForKey:APIKEYData];
      successBlock([[APIHSBCTotal alloc] initWithHSBCTotalData:dicSuccess]);
    }
  } apiFinish:^(id data) {
    NSDictionary *dictionaryTemp = data;
    NSInteger codeTemp= [[dictionaryTemp objectForKey:APIKEYCODE]integerValue];
    if (codeTemp ==0) {
      NSDictionary *dicSuccess = [dictionaryTemp objectForKey:APIKEYData];
      successBlock([APIHSBCTotal initWithHSBCData:dicSuccess]);
      
      //存入缓存
      [FileReadAndWrite storageDataWithFile:FILENAMECACHE_APIHSBCTOTAL andData:dictionaryTemp];
      
    }
    else
    {
      failureBlock(nil);
    }
  }];
  
}
@end
